package com.hxm.appGenealogy.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hxm.appGenealogy.Function.CommentFunction;
import com.hxm.appGenealogy.Function.DynamicFunction;
import com.hxm.appGenealogy.Function.FamilyFunction;
import com.hxm.appGenealogy.Function.PeopleFunction;
import com.hxm.appGenealogy.config.Constant;
import com.hxm.appGenealogy.config.ParmIntended;
import com.hxm.appGenealogy.config.ossConfig.DelOssConfig;
import com.hxm.appGenealogy.config.queryVo.QueryWrapperVO;
import com.hxm.appGenealogy.entity.*;
import com.hxm.appGenealogy.mapper.LikeMapper;
import com.hxm.appGenealogy.mapper.PhtotoMapper;
import com.hxm.appGenealogy.mapper.imagePhMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 发表文章业务模块;
 */
@Service
@Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRES_NEW)
public class DynamicService {


    @Autowired
    private DynamicFunction dynamicFunction;


    @Autowired
    private PeopleFunction peopleFunction;


    @Autowired
    private FamilyFunction familyFunction;


    @Autowired
    private CommentFunction commentFunction;

    @Autowired
    private PhtotoMapper photoMapper;


    @Autowired
    private imagePhMapper imageMapper;



    /**
     *发布动态;
     * @param dynamic
     * @return
     */
    public ResponDataVo insertAdd(DynamicVo dynamic) {
        //参数教验;
        String parmAnalysis = ParmIntended.parmAnalysis(dynamic, "peopleId","imagePhId");
        if (parmAnalysis != null) {
            return new ResponDataVo(parmAnalysis);
        }
        People people = peopleFunction.peopleGetByid(dynamic.getPeopleId());
        if (people == null) {
            return new ResponDataVo("当前发表动态的人不存在;");
        }
        if(people.getFamilyId()!=null){
            dynamic.setFamilyId(people.getFamilyId());
        }
        //获取家族的信息;
        if(people.getFamilyId()==null){
            return new ResponDataVo("您必须加入一个家族后才可以发表动态信息;");
        }
        if(dynamic.getImage()!=null&&dynamic.getType()!=null){
            Family family = (Family)familyFunction.selectByid(people.getFamilyId()).getData();
            if(family.getUsableSpace()<family.getUseSpace()){
                return new ResponDataVo("您的存储空间不足;");
            }
            if(family.getUseSpace()+dynamic.getImageSize()>family.getUsableSpace()){
                Double use =  family.getUsableSpace()-family.getUseSpace();
                return new ResponDataVo("您的存储空间不足当前剩余空间大小为"+use+"当前照片大小为"+dynamic.getImageSize());
            }
            //获取当前相册信息的数据;
            imagePh imagePh = imageMapper.selectById(dynamic.getImagePhId());
            if(imagePh==null){
                return new ResponDataVo("没有当前的相册的信息");
            }
            String image = dynamic.getImage();
            //0是照片 1是视频;
            if(dynamic.getType()==0){
                List<String> imageList = (List<String>)JSON.parse(image);
                imageList.forEach(t->{
                    Photo photo = new Photo();
                    photo.setIamge(t);
                    photo.setImagePhId(imagePh.getId());
                    photo.setTime(new Date());
                    photo.setSize(dynamic.getImageSize());
                    photo.setType(dynamic.getType());
                    photoMapper.insert(photo);
                });
                //增加照片的数量;
                imagePh.setQuantity(imagePh.getQuantity()+imageList.size());
                imageMapper.updateById(imagePh);
            }else {
                Photo photo = new Photo();
                photo.setIamge(dynamic.getImage());
                photo.setImagePhId(imagePh.getId());
                photo.setTime(new Date());
                photo.setSize(dynamic.getImageSize());
                photo.setType(dynamic.getType());
                photoMapper.insert(photo);
                //增加照片的数量;
                imagePh.setQuantity(imagePh.getQuantity()+1);
                imageMapper.updateById(imagePh);
            }
            //增加空间的存储量;
            family.setUseSpace(family.getUseSpace()+dynamic.getImageSize());
            familyFunction.updateById(family);
        }
        //设置发表文案的时间;
        dynamic.setTime(new Date());
        //设置点赞的数量;
        dynamic.setBrowse(0);
        //设置浏览量;
        dynamic.setPraise(0);
        //设置类型;
        //dynamic.setType(dynamic.getType());
        //设置评论的数量;
        dynamic.setCommentQuantity(0);
        dynamicFunction.insertDynamic(dynamic);
        return new ResponDataVo(dynamic);
    }

    /**
     * 查询家族的动态;
     * @param family
     * @return
     */
    public ResponDataVo   selectFamilyDynamic(FamilyVo family) {
        String parmAnalysis = ParmIntended.parmAnalysis(family, "id","peopleId");
        if (parmAnalysis != null) {
            return new ResponDataVo(parmAnalysis);
        }
        Family selectFamily = (Family) familyFunction.selectByid(family.getId()).getData();
        if (selectFamily == null) {
            return new ResponDataVo("不存在当前的家族的信息;");
        }
        Page page = new Page();
        page.setCurrent(family.getCurrent());
        page.setSize(family.getSize());
        Page selectPage = dynamicFunction.selectPage(page, JSON.toJSONString(new QueryWrapperVO().eq("family_id", family.getId()).orderByDesc("time")));
        //家族的动态;
        List <Dynamic>records = selectPage.getRecords();
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (Dynamic record : records) {
            Long peopleId = record.getPeopleId();
            People people = peopleFunction.peopleGetByid(peopleId);
            Map<String, Object> stringObjectMap = stringObjectMap(record, people,family.getPeopleId());
            mapList.add(stringObjectMap);
        }
        Map<String,Object> objectMap = new HashMap<>();
        objectMap.put("total",selectPage.getTotal());
        objectMap.put("dynamicList",mapList);
        return new ResponDataVo(objectMap);
    }


    /**
     * 查询个人发表的动态的信息;
     */
    public ResponDataVo selectPeopleDynamic(DynamicVo dynamicVo){
        String parmAnalysis = ParmIntended.parmAnalysis(dynamicVo, "peopleId");
        if(parmAnalysis!=null){
            return new ResponDataVo(parmAnalysis);
        }
        List<Dynamic> dynamics = dynamicFunction.selectGetListQuery(JSON.toJSONString(new QueryWrapperVO().eq("people_id", dynamicVo.getPeopleId()).orderByDesc("time")));
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (Dynamic record : dynamics) {
            Long peopleId = record.getPeopleId();
            People people = peopleFunction.peopleGetByid(peopleId);
            Map<String, Object> stringObjectMap = stringObjectMap(record, people,dynamicVo.getPeopleId());
            mapList.add(stringObjectMap);
        }
        return new ResponDataVo(mapList);
    }


    //查询一个动态的详情信息;
    public ResponDataVo selectDynamicMessage(Dynamic dynamic){
        String parmAnalysis = ParmIntended.parmAnalysis(dynamic, "id");
        if(parmAnalysis!=null){
            return new ResponDataVo(parmAnalysis);
        }
        Map<String,Object> stringObjectMap = new HashMap<>();
        Dynamic dynamic1 = dynamicFunction.selectByid(dynamic.getId());
        People people = peopleFunction.peopleGetByid(dynamic1.getPeopleId());
        //查询这个动态的详情的信息;
        stringObjectMap.put("avaver",people.getAvater());
        stringObjectMap.put("name",people.getName());
        stringObjectMap.put("headline",dynamic1.getHeadline());
        stringObjectMap.put("image",dynamic1.getImage());
        stringObjectMap.put("browse",dynamic1.getBrowse());
        stringObjectMap.put("praise",dynamic1.getPraise());
        stringObjectMap.put("commentQuantity",dynamic1.getCommentQuantity());
        stringObjectMap.put("time",new SimpleDateFormat(Constant.timeFormat).format(dynamic1.getTime()));
        stringObjectMap.put("dynamicPeopleId",dynamic1.getPeopleId());
        stringObjectMap.put("longitude",dynamic1.getLongitude());
        stringObjectMap.put("latitude",dynamic1.getLatitude());
        stringObjectMap.put("geographic",dynamic1.getGeographic());
        if(dynamic1.getEvent()==1){
            stringObjectMap.put("event",true);
        }else {
            stringObjectMap.put("event",false);
        }
        List<Comment> commentList = commentFunction.selectGetListQuery(JSON.toJSONString(new QueryWrapperVO().eq("dynamic_id", dynamic1.getId()).orderByDesc("time")));
        List<Map<String,Object>> mapList = new ArrayList<>();
        for (Comment comment : commentList) {
            Map<String,Object> map = new HashMap<>();
            Long peopleId = comment.getPeopleId();
            People people1 = peopleFunction.peopleGetByid(peopleId);
            map.put("commentName",people1.getName());
            map.put("commentAvaver",people1.getAvater());
            map.put("comment",comment.getContent());
            map.put("commentTime",new SimpleDateFormat(Constant.timeFormat).format(comment.getTime()));
            map.put("commentPeopleId",comment.getPeopleId());
            mapList.add(map);
        }
        stringObjectMap.put("commentList",mapList);
        //添加这个动态的浏览量;
        dynamic1.setBrowse(dynamic1.getBrowse()+1);
        dynamicFunction.updateByid(dynamic1);
        return new ResponDataVo(stringObjectMap);
    }


    @Autowired
    private LikeMapper likeMapper;
    /**
     * 动态初始化;
     * @param dynamic1
     * @param people
     * @return
     */
    public Map<String,Object> stringObjectMap(Dynamic dynamic1,People people,Long peopleId){
        Map<String,Object> stringObjectMap = new HashMap<>();
        //查询这个动态的详情的信息;
        stringObjectMap.put("avaver",people.getAvater());
        stringObjectMap.put("name",people.getName());
        stringObjectMap.put("headline",dynamic1.getHeadline());
        stringObjectMap.put("image",dynamic1.getImage());
        stringObjectMap.put("browse",dynamic1.getBrowse());
        stringObjectMap.put("praise",dynamic1.getPraise());
        stringObjectMap.put("commentQuantity",dynamic1.getCommentQuantity());
        stringObjectMap.put("time",new SimpleDateFormat(Constant.timeFormat).format(dynamic1.getTime()));
        stringObjectMap.put("dynamicId",dynamic1.getId());
        stringObjectMap.put("dynamicPeopleId",dynamic1.getPeopleId());
        stringObjectMap.put("longitude",dynamic1.getLongitude());
        stringObjectMap.put("latitude",dynamic1.getLatitude());
        stringObjectMap.put("type",dynamic1.getType());
        //地理位置;
        stringObjectMap.put("geographic",dynamic1.getGeographic());
        //0是重大事件,1不是重大事件;
        if(dynamic1.getEvent()==1){
            stringObjectMap.put("event",true);
        }else {
            stringObjectMap.put("event",false);
        }
        if(peopleId!=null){
            People people1 = peopleFunction.peopleGetByid(peopleId);
            //判断当前的人是否给他点了赞;
            LambdaQueryWrapper<Like> likeLambdaQueryWrapper = new LambdaQueryWrapper<>();
            likeLambdaQueryWrapper.eq(Like::getPeopleId,peopleId).eq(Like::getDynamicId,dynamic1.getId());
            Like like = likeMapper.selectOne(likeLambdaQueryWrapper);
            if(like!=null){
                //1是点赞了;
                stringObjectMap.put("islike",true);
            }else {
                //0是没有点赞;
                stringObjectMap.put("islike",false);
            }
        }
        return stringObjectMap;
    }


    @Autowired
    private imagePhMapper imagePhMapper;

    @Autowired
    private PhtotoMapper phtotoMapper;

    @Autowired
    private DelOssConfig delOssConfig;

    /**
     * 删除动态;
     * @param dynamic
     * @return
     */
    public ResponDataVo delDynamic(Dynamic dynamic){
        String parmAnalysis = ParmIntended.parmAnalysis(dynamic, "id","peopleId");
        //参数信息的教验;
        if(parmAnalysis!=null){
            return new ResponDataVo(parmAnalysis);
        }
        Dynamic dynamicData = dynamicFunction.selectByid(dynamic.getId());
        if(dynamicData==null){
            return new ResponDataVo("没有当前的动态的信息;");
        }
        //判断这个人是否可以删除这条动态(判断是不是当前的登录者发表的文章;)
        if(!dynamic.getPeopleId().equals(dynamicData.getPeopleId())){
            return new ResponDataVo("您不可以删除族人发布的文章,您只可以删除自己的文章;");
        }
        List<String> imageList =new ArrayList<>();
        if(dynamicData.getType()!=null){
            if(dynamicData.getType()==0&&dynamicData.getImage()!=null){
                imageList = (List<String>)JSON.parse(dynamicData.getImage());
            }
            if(dynamicData.getImage()!=null&&dynamicData.getType()==1){
                imageList.add(dynamicData.getImage());
            }
        }
        //获取照片的信息;
        Double size = 0.00;
        try {
            if(imageList.size()>0){
                for (String image : imageList) {
                    Photo photo = phtotoMapper.selectOne(new QueryWrapper<Photo>().eq("iamge", image));
                    if(photo!=null){
                        size=photo.getSize();
                        //删除当前的照片的数据;
                        photoMapper.deleteById(photo.getId());
                        //修改照片的数量;
                        imagePh imagePh = imagePhMapper.selectById(photo.getImagePhId());
                        imagePh.setQuantity(imagePh.getQuantity()-1);
                        imagePhMapper.updateById(imagePh);
                        //在OSS存储之上删除这些照片;
                        //System.out.println(image.length()+"()()()()()()()()()()");
                        String imageJpgUrl = image.substring(34,57);
                        delOssConfig.delImage(imageJpgUrl);
                    }
                }
            }
            //增加存储的空间的大小;
            Family family = (Family)familyFunction.selectByid(dynamicData.getFamilyId()).getData();
            if(size!=0.00){
                family.setUseSpace(family.getUseSpace()-size);
                familyFunction.updateById(family);
            }
            //删除当前的动态的信息;
            dynamicFunction.dedl(dynamicData);
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponDataVo("你好美女,服务器异常哦!");
        }
        return new ResponDataVo(true);
    }



}







